import axios from 'axios';
import { ElMessage, ElLoading } from 'element-plus';
import { getStorage } from '@/utils/storage';

// 创建 axios 实例
const http = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 8000
});

// 请求拦截器
http.interceptors.request.use(
  (config) => {
    // 替换原 loading 逻辑
    showLoading('加载中');
    // 添加 token、tenant-id 等 header
    const token = getStorage('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    config.headers['tenant-id'] = import.meta.env.VITE_TENANT_ID;
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
http.interceptors.response.use(
  (response) => {
    // 替换原 loading 逻辑
    hideLoading();
    // 处理业务逻辑（如 token 刷新）
    if (response.data.code !== 0) {
      showToast(response.data.msg || '请求失败', 'error');
      return Promise.reject(response.data);
    }
    return response.data;
  },
  (error) => {
    hideLoading();
    showToast(error.message || '网络错误', 'error');
    return Promise.reject(error);
  }
);

// 替换 Loading 管理
let loadingCount = 0;
let loadingInstance: ReturnType<typeof ElLoading.service>;

function showLoading(msg: string) {
  loadingCount++;
  if (loadingCount === 1) {
    loadingInstance = ElLoading.service({
      text: msg,
      background: 'rgba(0, 0, 1, 0.3)',
      lock: true
    });
  }
}

function hideLoading() {
  if (loadingCount > 0) loadingCount--;
  if (loadingCount === 0) {
    loadingInstance?.close();
  }
}

// 替换 uni.showToast
function showToast(msg: string, type: 'success' | 'error' = 'error') {
  ElMessage({
    message: msg,
    type: type,
    duration: 2000,
    showClose: true
  });
}
export default http;